package sim.core.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {
	public static <T> T mapToBean(Map<String, Object> map, Class<T> beanClass) {
		if (null == map || map.size() == 0) {
			throw new NullPointerException("map data can not null");
		}
		T obj = null;
		try {
			obj = (T) beanClass.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				Method setter = property.getWriteMethod();
				if (setter != null) {
					Object value = map.get(property.getName());
					setter.invoke(obj, value);
				}
			}
		} catch (InstantiationException | IllegalAccessException | IntrospectionException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return obj;
	}

	public static Map<String, Object> beanToMap(Object bean) {
		if (bean == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(bean);
					map.put(key, value);
				}
			}
		} catch (IllegalAccessException | IntrospectionException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		return map;
	}
}
